package com.tanhua.management.controller;



import com.tanhua.management.service.AdminService;
import com.tanhua.management.utils.Captcha;
import com.tanhua.management.vo.AdminVo;
import com.tanhua.management.vo.ErrorResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("system/users")
public class AdminController {

    @Autowired
    private AdminService adminService;

    /**
     * 功能描述: 生成验证码图片
     * @param uuid              浏览器随机生成
     * @param response          响应体
     * @param request           请求体
     * @Return: void            无返回参数
     * @throws:                 异常
     */
    @GetMapping("verification")
    public void verification(@RequestParam(name="uuid") String uuid, HttpServletResponse response, HttpServletRequest request){
        //响应头
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        Captcha captcha= new Captcha();

        //生成图片
        String ranCaptcha= captcha.getRandcode(request,response);
        //调用adminService里面的saveVerification方法,传入uuid和验证码
        this.adminService.saveVerification(uuid,ranCaptcha);
    }

    /**
     * 功能描述: login
     * @param param      用户名,密码,验证码
     * @Return: {@link ResponseEntity<Object>}
     * @throws:
     */
    @PostMapping("login")
    public ResponseEntity<Object> login(@RequestBody Map<String, String> param) {
        try {
            // 获取参数
            String username = param.get("username");
            String password = param.get("password");
            String code = param.get("verificationCode");
            String uuid = param.get("uuid");
            //返回token
            String token = this.adminService.login(username, password, code, uuid);
            // 不为空
            if (StringUtils.isNotEmpty(token)) {
                Map<String, Object> result = new HashMap<>();
                result.put("token", token);
                // 返回前台
                return ResponseEntity.ok(result);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        ErrorResult.ErrorResultBuilder builder = ErrorResult.builder().errCode("000000").errMessage("登录失败");
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(builder.build());
    }

    /**
     * 用户基本信息
     *
     * @param token        令牌
     * @return              {@link ResponseEntity<Object>}
     */
    @PostMapping("profile")
    public ResponseEntity<AdminVo> profile (@RequestHeader(required = false, name = "Authorization") String token) {
        try {
            // 设置token
            String newToken = token.replace("Bearer ", "");
            AdminVo adminVo = adminService.queryAdminByToken(newToken);
            if (null != adminVo) {
                return ResponseEntity.ok(adminVo);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
    }

    /**
     * 登出
     *
     * @param token         令牌
     */
    @PostMapping("logout")
    private void logout(@RequestHeader("Authorization") String token){
        String newToken = token.replace("Bearer ", "");
        this.adminService.removeToken(token);
    }
}
